package org.jeecg.modules.kaoqtj.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import lombok.extern.flogger.Flogger;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.agCarGps.entity.AgCarGps;
import org.jeecg.modules.kaoqgz.entity.AgKaoqgz;
import org.jeecg.modules.kaoqgz.service.IAgKaoqgzService;
import org.jeecg.modules.kaoqtj.entity.AgKaoqtj;
import org.jeecg.modules.kaoqtj.service.IAgKaoqtjService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.qiangzlw.service.IAgQiangzlwService;
import org.jeecg.modules.tongxjl.entity.AgTongxjl;
import org.jeecg.modules.tongxjl.service.IAgTongxjlService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 考勤统计
 * @Author: jeecg-boot
 * @Date: 2020-10-13
 * @Version: V1.0
 */
@Api(tags = "考勤统计")
@RestController
@RequestMapping("/kaoqtj/agKaoqtj")
@Slf4j
public class AgKaoqtjController extends JeecgController <AgKaoqtj, IAgKaoqtjService> {
    @Autowired
    private IAgTongxjlService agTongxjlService;

    @Autowired
    private IAgKaoqgzService agKaoqgzService;

    @Autowired
    private IAgKaoqtjService agKaoqtjService;


    List <String> middleDays(String startday, String endday) {
        List <String> daysarr = new ArrayList <>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Calendar cld = Calendar.getInstance();
            cld.setTime(sdf.parse(endday));
            cld.add(Calendar.DAY_OF_MONTH, 1);
            Date enddate = cld.getTime();
            Date temp = sdf.parse(startday);
            int onedaylength = 86400000;

            while (temp.before(enddate)) {
                daysarr.add(sdf.format(temp));
                long timestamp = temp.getTime();
                timestamp += onedaylength;
                temp = new Date(timestamp);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return daysarr;
    }

    //获取当前月第一天
    public static Date getFirstDayOfMonth(Date someDate) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(someDate); //
        ca.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDate = ca.getTime();
        ca.add(Calendar.MONTH, 1);
        ca.add(Calendar.DAY_OF_MONTH, -1);
        Date lastDate = ca.getTime();
        return firstDate;
    }


    /**
     * 分页列表查询
     * <p>
     * //* @param agKaoqtj
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "考勤统计-分页列表查询")
    @ApiOperation(value = "考勤统计-分页列表查询", notes = "考勤统计-分页列表查询")
    @GetMapping(value = "/list")
    @ResponseBody
    // public Result <?> queryPageList(AgKaoqtj agKaoqtj,
    public Result <?> queryPageList(AgTongxjl agTongxjl,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {


        String tongxsj_begin = req.getParameter("tongxsj_begin");
        String tongxsj_end = req.getParameter("tongxsj_end");
        Date begin=null;
        Date end=null;



        log.info("考勤统计开始时间" + tongxsj_begin);
        log.info("考勤统计结束时间" + tongxsj_end);


        if (tongxsj_begin == null || tongxsj_end == null) {
            String today = DateUtils.formatDate(new Date());
            //tongxsj_begin =DateUtils.formatDate(getFirstDayOfMonth(new Date()));
            tongxsj_begin = today  + " 00:00:00";
            // tongxsj_end = today;
            tongxsj_end = today  + " 23:59:59";
        }else{
            tongxsj_begin=tongxsj_begin+" 00:00:00";
            tongxsj_end = tongxsj_end  + " 23:59:59";
        }
        try {
           // begin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tongxsj_begin);
            begin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tongxsj_begin);
          //  end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tongxsj_end);
            end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tongxsj_end);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String shangbsj = null;
        String xiabsj = null;

        try {
            long t1 = System.currentTimeMillis();
            //考勤规则
            List <AgKaoqgz> agKaoqgz = agKaoqgzService.list(new QueryWrapper <AgKaoqgz>());
            // System.out.println(agKaoqgz);

            shangbsj = agKaoqgz.get(0).getShagnbsj();
            //String shangbsj="2020-12-08T00:30:00.000Z";
            shangbsj = shangbsj.replace("Z", " UTC");
            Date date = null;
            try {
                date = DateUtils.parseDate(shangbsj, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String chiddsfznbscd = agKaoqgz.get(0).getChiddsfznbscd();
            //String chiddsfznbscd="5";
            long chidsj = Integer.valueOf(chiddsfznbscd);
            shangbsj = new SimpleDateFormat("HH:mm:ss").format(date.getTime() + chidsj * 60 * 1000);
            //  System.out.println("考勤上班时间" + shangbsj);


            xiabsj = agKaoqgz.get(0).getXiabsj();
            //String xiabsj="2020-12-08T10:00:00.000Z";

            String tiqdsfznbszt = agKaoqgz.get(0).getTiqdsfznbszt();
            //String tiqdsfznbszt="5";


            xiabsj = xiabsj.replace("Z", " UTC");
            Date date2 = null;
            try {
                date2 = DateUtils.parseDate(xiabsj, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long zaotsj = Integer.valueOf(tiqdsfznbszt);
            xiabsj = new SimpleDateFormat("HH:mm:ss").format(date2.getTime() - zaotsj * 60 * 1000);
            //   System.out.println("考勤下班时间" + xiabsj);
            long t2 = System.currentTimeMillis();
            long t = t2 - t1;
            //  System.out.println(t);
        } catch (NumberFormatException e) {

            System.out.println("考勤规则时间为空！" + "\n" + e);
            throw new JeecgBootException("请查看考勤规则时间参数-参数不能为空");
            // return  Result.ok().success("请查看考勤规则时间参数-参数不能为空");
        }


        List <AgKaoqtj> list = new ArrayList <>();


        AgKaoqtj agKaoqtj = new AgKaoqtj();
        QueryWrapper <AgKaoqtj> queryWrapper=new QueryWrapper <>();

        if (agTongxjl.getBum() != null&&agTongxjl.getBum()!="") {
            agKaoqtj.setBum(agTongxjl.getBum());

            queryWrapper.eq("bum", agKaoqtj.getBum()).between("shangbsj", begin,end);
        }
        if (agTongxjl.getXingm() != null&&agTongxjl.getXingm()!="") {
            agKaoqtj.setXingm(agTongxjl.getXingm());
            queryWrapper.eq("xingm", agKaoqtj.getXingm()).between("shangbsj", begin,end);
        }
        if (agTongxjl.getBum() != null&&agTongxjl.getBum()!=""&&agTongxjl.getXingm() != null&&agTongxjl.getXingm()!="") {
            agKaoqtj.setBum(agTongxjl.getBum());
            agKaoqtj.setXingm(agTongxjl.getXingm());
            queryWrapper.eq("bum", agKaoqtj.getBum()).eq("xingm",agTongxjl.getXingm()).between("shangbsj", begin,end);
        }
        if (agTongxjl.getBum() == null&&agTongxjl.getXingm() == null){
            queryWrapper.between("shangbsj", begin,end);
        }


       // QueryWrapper <AgKaoqtj> queryWrapper = QueryGenerator.initQueryWrapper(agKaoqtj, req.getParameterMap());

        long t1 = System.currentTimeMillis();
        Map <String, List <AgKaoqtj>> result = agKaoqtjService.list(queryWrapper).parallelStream()
                //	.filter(p -> p.getShenf().equals("1"))
                .filter(p -> p.getXingm() != null)
                .filter(p -> p.getRenybh() != null)
                .collect(Collectors.groupingBy(AgKaoqtj::getRenybh));
        long t2 = System.currentTimeMillis();
        log.info("考勤统计select时间" + (t2 - t1));
        //System.out.println("考勤统计select时间" + (t2 - t1));

        String finalShangbsj = shangbsj;
        String finalXiabsj = xiabsj;
        String finalTongxsj_begin = tongxsj_begin;
        String finalTongxsj_end = tongxsj_end;
        result.forEach((k, v) ->
        {
            AgKaoqtj tmp = new AgKaoqtj();
            AgKaoqtj obj = v.get(0);
            tmp.setId(k);
            // System.out.println(obj.getXingm());
            tmp.setXingm(obj.getXingm());
            tmp.setBum(obj.getBum());

            int chid = 0;
            int zaot = 0;
            int zhengc = 0;
            int queq = 0;
            int loudk = 0;

            List <String> day_of_month = middleDays(finalTongxsj_begin, finalTongxsj_end);
            for (String today : day_of_month) {
                Map <String, Object> map = new HashMap <>();
                List <AgKaoqtj> list2 = v.stream()
                        .filter(p -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(p.getShangbsj()).startsWith(today))
                        .sorted(Comparator.comparing(AgKaoqtj::getShangbsj))
                        .collect(Collectors.toList());
                if (list2.size() == 0) {
                    queq++;
                    continue;
                }

                if (list2.get(0).getShangbsj() == null || list2.get(0).getXiabsj() == null) {
                    loudk++;
                }

                Date shangb = list2.get(0).getShangbsj();
                //  System.out.println("上班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(shangb));
                if (shangb.after(DateUtils.str2Date(today + " " + finalShangbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
                    chid++;

                // System.out.println(DateUtils.str2Date(today +" "+ finalSb, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
                if (list2.get(0).getXiabsj() != null) {
                    Date xiab = list2.get(0).getXiabsj();
                    //  System.out.println("下班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(xiab));
                    if (xiab.before(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
                        zaot++;

                    if (shangb.before(DateUtils.str2Date(today + " " + finalShangbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))) && xiab.after(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
                        zhengc++;
                }

                if (list2.size() > 1) {
                    Date xiab = list2.get(list2.size() - 1).getXiabsj();
                    //  System.out.println("下班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(xiab));
                    if (xiab.before(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
                        zaot++;

                    if (shangb.before(DateUtils.str2Date(today + " " + finalShangbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))) && xiab.after(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
                        zhengc++;
                }
            }

            tmp.setZhengcts(zhengc + "");
            tmp.setChidcs(chid + "");
            tmp.setZaotcs(zaot + "");
            tmp.setLoudkcs(loudk + "");
            tmp.setQueqcs(queq + "");
            tmp.setGognzrjbcs("0");
            tmp.setJiejrjbcs("0");

            list.add(tmp);
        });

        IPage <AgKaoqtj> pageList = new Page <>();
        pageList.setRecords(list);
        pageList.setTotal(list.size());

        return Result.ok(pageList);

//        QueryWrapper <AgTongxjl> queryWrapper = QueryGenerator.initQueryWrapper(agTongxjl, req.getParameterMap());
//
//
//        long t1 = System.currentTimeMillis();
//        Map <String, List <AgTongxjl>> result = agTongxjlService.list(queryWrapper).parallelStream()
//                .filter(p -> p.getShenf().equals("1"))
//                .filter(p -> p.getShibzp() != null)
//                .collect(Collectors.groupingBy(AgTongxjl::getShibzp));
//        long t2 = System.currentTimeMillis();
//        //  System.out.println("%%%%" + (t2 - t1));
//
//        String finalShangbsj = shangbsj;
//        String finalXiabsj = xiabsj;
//        result.forEach((k, v) -> {
//            AgKaoqtj tmp = new AgKaoqtj();
//            AgTongxjl obj = v.get(0);
//            tmp.setId(k);
//            System.out.println(obj.getXingm());
//            tmp.setXingm(obj.getXingm());
//            tmp.setBum(obj.getBum());
//
//            int chid = 0;
//            int zaot = 0;
//            int zhengc = 0;
//            int queq = 0;
//
//            List <String> day_of_month = middleDays(tongxsj_begin, tongxsj_end);
//            for (String today : day_of_month
//            ) {
//                Map <String, Object> map = new HashMap <>();
//                List <AgTongxjl> list2 = v.stream()
//                        .filter(p -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(p.getTongxsj()).startsWith(today))
//                        .sorted(Comparator.comparing(AgTongxjl::getTongxsj))
//                        .collect(Collectors.toList());
//                if (list2.size() == 0) {
//                    queq++;
//                    continue;
//                }
//
//                Date shangb = list2.get(0).getTongxsj();
//                System.out.println("上班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(shangb));
//                if (shangb.after(DateUtils.str2Date(today + " " + finalShangbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
//                    chid++;
//
//                // System.out.println(DateUtils.str2Date(today +" "+ finalSb, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
//
//                if (list2.size() > 1) {
//                    Date xiab = list2.get(list2.size() - 1).getTongxsj();
//                    System.out.println("下班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(xiab));
//                    if (xiab.before(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
//                        zaot++;
//
//                    if (shangb.before(DateUtils.str2Date(today + " " + finalShangbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))) && xiab.after(DateUtils.str2Date(today + " " + finalXiabsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))))
//                        zhengc++;
//                }
//            }
//
//            tmp.setZhengcts(zhengc + "");
//            tmp.setChidcs(chid + "");
//            tmp.setZaotcs(zaot + "");
//            tmp.setLoudkcs("0");
//            tmp.setQueqcs(queq + "");
//            tmp.setGognzrjbcs("0");
//            tmp.setJiejrjbcs("0");
//
//            list.add(tmp);
//        });
//
//        IPage <AgKaoqtj> pageList = new Page <>();
//        pageList.setRecords(list);
//        pageList.setTotal(list.size());
//
//        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param agKaoqtj
     * @return
     */
    @AutoLog(value = "考勤统计-添加")
    @ApiOperation(value = "考勤统计-添加", notes = "考勤统计-添加")
    @PostMapping(value = "/add")
    public Result <?> add(@RequestBody AgKaoqtj agKaoqtj) {
        agKaoqtjService.save(agKaoqtj);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param agKaoqtj
     * @return
     */
    @AutoLog(value = "考勤统计-编辑")
    @ApiOperation(value = "考勤统计-编辑", notes = "考勤统计-编辑")
    @PutMapping(value = "/edit")
    public Result <?> edit(@RequestBody AgKaoqtj agKaoqtj) {
        agKaoqtjService.updateById(agKaoqtj);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "考勤统计-通过id删除")
    @ApiOperation(value = "考勤统计-通过id删除", notes = "考勤统计-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result <?> delete(@RequestParam(name = "id", required = true) String id) {
        agKaoqtjService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "考勤统计-批量删除")
    @ApiOperation(value = "考勤统计-批量删除", notes = "考勤统计-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result <?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.agKaoqtjService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "考勤统计-通过id查询")
    @ApiOperation(value = "考勤统计-通过id查询", notes = "考勤统计-通过id查询")
    @GetMapping(value = "/queryById")
    public Result <?> queryById(@RequestParam(name = "id", required = true) String id) {
        AgKaoqtj agKaoqtj = agKaoqtjService.getById(id);
        if (agKaoqtj == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(agKaoqtj);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param agKaoqtj
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AgKaoqtj agKaoqtj) {
        return super.exportXls(request, agKaoqtj, AgKaoqtj.class, "考勤统计");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result <?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AgKaoqtj.class);
    }

}
